# ------------------------------------------------------------------------------
# Tunes 5 GBM models (one excluding each fold)
# Updates author: Cassidy Shubatt <cshubatt@gmail.com>
# To run: bsub -q big -R "rusage[mem=10000]" bash 03_tune_gbm.sh {outcome} {split} {restriction}
# ------------------------------------------------------------------------------

# Seeding ----------------------------------------------------------------------
set.seed(1)

# Libraries --------------------------------------------------------------------
message("Loading libraries...")
library(yaml)
library(data.table)
library(tidyverse)
library(glue)
library(Matrix)
library(xgboost)
library(optparse)
library(here) # here() relative filepaths
library(testit) # assert functtion

u <- modules::use(here("lib", "util.R"))

# Command Line Args ------------------------------------------------------------
arg_config <- list(
  make_option("--outcome", type = "character"),
  make_option("--split", type = "character"),
  make_option("--restriction", type = "character")
)
arg_parser <- OptionParser(option_list = arg_config)
arg_list <- parse_args(arg_parser)
split <- arg_list$split

# Directories ------------------------------------------------------------------
message("Establishing directories...")
paths <- read_yaml(here("lib", "filepaths.yml"))
cohort_dir <- file.path(paths$modeling$oos, "cohorts", arg_list$split)
features_dir <- file.path(paths$features$dir, arg_list$split)
tuning_dir <- file.path(
  paths$modeling$oos, "tuning", arg_list$split, arg_list$restriction
)
assert("Tuning directory exists", dir.exists(tuning_dir))
build_models_dir <- here::here("code", "03_analysis", "01_build_models")

# Load Data --------------------------------------------------------------------
message("Loading data...")
config <- read_yaml(
  file.path(build_models_dir, "model_config", glue("{arg_list$outcome}.yml"))
)
ds <- config$downsample
ids <- readRDS(file.path(cohort_dir, glue("train_cohort_{ds}.rds")))
x <- readRDS(file.path(features_dir, glue("train_features_{ds}.rds")))

if(arg_list$restriction == "dropcc"){
  # drop chief complaint features
  keep_feats <- which(!grepl("ed_enc_t0d", colnames(x)))
  x <- x[, keep_feats]
}else if(arg_list$restriction == "justcc"){
  keep_feats <- which(grepl("ed_enc_t0d", colnames(x)))
  x <- x[, keep_feats]
}else if(arg_list$restriction == "dem"){
  keep_feats <- which(grepl("dem_", colnames(x)))
  x <- x[, keep_feats]
}else if(arg_list$restriction == "enc"){
  keep_feats <- which(grepl("enc_", colnames(x)) & !grepl("_cc_", colnames(x)))
  x <- x[, keep_feats]
}

# Subset Data ------------------------------------------------------------------
message("Subsetting data...")
keep_pop <- switch(config$population,
  all = rep(TRUE, nrow(ids)),
  tested = ids$test_010_day == TRUE,
  untested = ids$test_010_day == FALSE
)

keep_pop <- keep_pop & !ids$exclude_modeling
keep <- which(keep_pop)

x <- x[keep, ]
ids <- ids[keep, ]

# Prep tuning grid -------------------------------------------------------------
message("Preparing tuning grid...")
tuning_design_raw <- do.call(crossing, config$gbm)

# Tuning -----------------------------------------------------------------------
message("Tuning GBMs...")
for (i in 1:5) {
  message("Running model excluding fold ", i, "...")
  keep <- which(ids$train_fold != i & !(ids$in_ensemble))
  ids_sub <- ids[keep, ]
  x_sub <- x[keep, ]
  ids_sub <- ids_sub %>%
    mutate(train_fold = ifelse(train_fold > i, train_fold - 1, train_fold))

  message("Checking for previous tuning results...")
  previous_tuning_path <- file.path(
    tuning_dir,
    glue("gbm__{target}__{population}__{i}.rds", .envir = config)
  )
  previous_tuning <- tryCatch(readRDS(previous_tuning_path),
    warning = function(c) {
      message("No previous tuning...")
      tuning_design_raw[0, ]
    }
  )

  tuning_design <- anti_join(tuning_design_raw, previous_tuning,
    by = names(tuning_design_raw)
  )

  folds <- map(unique(ids_sub$train_fold), ~ which(ids_sub$train_fold == .x))
  tuning_result <- pmap(tuning_design, xgb.cv,
    data = x_sub,
    label = ids_sub[[config$target]],
    folds = folds,
    nrounds = 10000L,
    early_stopping_rounds = 20L,
    objective = "binary:logistic"
  )

  tuning_design$logloss <- map(tuning_result, ~ unlist(.x$evaluation_log))
  tuning_design$num_iterations <- map(tuning_design$logloss, seq_along)
  tuning_output <- bind_rows(previous_tuning, tuning_design)

  message("Saving GBM tuning excluding fold ", i, " to ", previous_tuning_path, "...")
  saveRDS(tuning_output, previous_tuning_path, compress = FALSE)
}

# Done -------------------------------------------------------------------------
message("Done.")
